package com.rxjava.http;

import com.alibaba.fastjson.JSON;
import com.rxjava.bean.User;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by kkmike999 on 16/3/21.
 */
public class UserModel {

    /**
     * 从本地获取User实例
     *
     * @return
     */
    public rx.Observable<User> getUserFromDb() {

        String string = "{ \"uid\":1, \"name\":\"小明\"}";

        rx.Observable<String> observable = rx.Observable.just(string);

        rx.Observable<User> userObservable = observable

                .map(new Func1<String, User>() {
                    public User call(String json) {
                        User user = JSON.parseObject(json, User.class);

                        return user;
                    }
                });

        return userObservable;
    }

    public rx.Observable<User> getUserFromDb2() {

        String string = "{ \"uid\":1, \"name\":\"小明\"}";

        return rx.Observable
                .just(string)
                .map(new Func1<String, User>() {
                    public User call(String json) {
                        User user = JSON.parseObject(json, User.class);

                        return user;
                    }
                });
    }

    /**
     * 从服务器获取User json
     *
     * @return
     */
    public Observable<User> loadUser() {
        System.out.println("loadUser");

        IUserHttp userHttp = getUserHttp();

        Observable<User> observable =
                userHttp.loadUserFromServer()
                        .map(new Func1<String, User>() {
                            public User call(String json) {
                                System.out.println(Thread.currentThread());

                                return JSON.parseObject(json, User.class);
                            }
                        });

        return observable;
    }

    IUserHttp getUserHttp(){
        return new UserHttp();
    }
}
